import Notify from 'weapp/notify/notify';

App({
  onLaunch() {},
  globalData: {
    userInfo: null,
    openId: '',
    systemInfo: wx.getWindowInfo() || {
      statusBarHeight: 0
    }, // 设备信息
  },
  cache: {
    AUTH_USER: 'auth_user', // 用户信息
    AUTH_OPENID: 'auth_openid' // 微信openId
  },
  apiRoot: 'https://logi.sqcdrj.com/',
  // apiRoot: 'http://192.168.8.157:8033/',
  // apiRoot: 'http://localhost:8013/',
  showNotify: function (message, type = 'danger', duration = 2000, top = 0) {
    Notify({
      type,
      message,
      duration,
      top,
    });
  },
  getOpenId() {
    let _this = this;
    let needUserInfo = false; // 是否获取用户基本信息
    if (needUserInfo) {
      // 推荐使用wx.getUserProfile获取用户信息，开发者每次通过该接口获取用户个人信息均需用户确认，开发者妥善保管用户快速填写的头像昵称，避免重复弹窗
      wx.getUserProfile({
        desc: '展示用户信息', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
        success: (res) => {
          _this.globalData.userInfo = res.userInfo;

          //调用登录接口
          wx.login({
            success: function (res) {
              //换取openid & session_key
              wx.request({
                url: _this.apiRoot + 'Customer/OnLogin',
                method: 'POST',
                data: {
                  code: res.code
                },
                success: function (json) {
                  if (json.data.success) {
                    _this.globalData.openId = json.data.openId;
                    wx.navigateTo({
                      url: '/pages/bind/index'
                    })
                  } else {
                    console.log('储存session失败！', json);
                  }
                }
              })
            }
          })
        }
      })
    } else {
      //调用登录接口
      wx.login({
        success: function (res) {
          //换取openid & session_key
          wx.request({
            url: _this.apiRoot + 'Customer/OnLogin',
            method: 'POST',
            data: {
              code: res.code
            },
            success: function (json) {
              if (json.data.success) {
                _this.globalData.openId = json.data.openId;
                wx.navigateTo({
                  url: '../bind/index'
                })
              } else {
                console.log('储存session失败！', json);
              }
            }
          })
        }
      })
    }
  },
  ajax(opts) {
    let _this = this;
    const {
      method,
      headers,
      data,
      verifyToken,
      timeout = 5000,
      again = true
    } = opts;
    const _headers = headers || {};
    const {
      Token
    } = wx.getStorageSync(_this.cache.AUTH_USER);
    _headers.token = Token || '';
    if (verifyToken && !Token) {
      wx.switchTab({
        url: '/pages/account/index'
      });
      return;
    }
    wx.showLoading({
      title: opts.msg || "加载中..."
    });
    wx.request({
      url: `${_this.apiRoot}${opts.url}`,
      data,
      method: method || 'POST',
      header: _headers,
      timeout,
      success(resp) {
        wx.hideLoading();
        const {
          data
        } = resp;
        if (data && !data.result && data.msg === '用户无效') {
          try {
            wx.clearStorageSync();
            _this.getOpenId(); //清除之后重新获取openId,不然登录页面获取不到openId
          } catch (e) {
            wx.showToast({
              title: "清空失败！"
            });
          }
          return;
        }
        opts.success && opts.success(data);
      },
      fail(resp) {
        const {
          errMsg
        } = resp;
        if (errMsg && errMsg === 'request:fail timeout' && again) {
          _this.ajax(opts);
          return;
        }
        wx.hideLoading();
        opts.fail && opts.fail(resp);
      },
      complete() {
        opts.complete && opts.complete();
      }
    });
  },
  upload(opts) {
    let _this = this;
    const {
      filePath,
      name,
      header,
      formData,
      timeout = 2000
    } = opts;
    const _header = header || {};
    const {
      Token
    } = wx.getStorageSync(_this.cache.AUTH_USER);
    _header.token = Token || '';
    wx.uploadFile({
      url: `${_this.apiRoot}/Picture/AsyncUpload`,
      filePath,
      name: name || 'qqfile',
      header: _header,
      formData,
      timeout,
      success(resp) {
        const {
          data,
          statusCode
        } = resp;
        if (opts.success && statusCode === 200) opts.success(JSON.parse(data));
      },
      fail(resp) {
        const {
          errMsg
        } = resp;
        if (errMsg && errMsg === 'request:fail timeout') {
          _this.ajax(opts);
          return;
        }
        opts.fail && opts.fail(resp);
      },
      complete() {
        opts.complete && opts.complete();
      }
    })
  }
})